<?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\Container;
use Zend\View\Model\ViewModel;
require_once __DIR__.'/../Resource/produit/functions.php';

class ProduitController extends AbstractActionController
{

    public function getEntityManager()
    {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()
                ->get('doctrine.entitymanager.orm_default');
        }
        return $this->em;
    }
    
    public function indexAction()
    {   
        /*
        Filtres a implementer:
            categorie   fait.
            etat        fait.
            prix        fait en partie. Reste le slider à integrer.
            taille      non implémenté.
        Autres idées de filtre : http://www.laredoute.fr/achat-femme-manteau-blouson.aspx?categoryid=22906255
        */ 
        
        $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
        $categoriesEnBase = $em->getRepository('Application\Model\Entity\Categorie')->findAll();
        $etatsEnBase = $em->getRepository('Application\Model\Entity\Etat')->findAll();
        array_pop($etatsEnBase); // TODO : use query builder
        
        $produitsEnBase = array();
        
        $manager = \Zend\Session\Container::getDefaultManager();
        if (!$manager->sessionExists()) {
            $manager->start();
        }
        $filtresContainer = new Container('filters');
        
        $request = $this->getRequest();
        
        if ($request->isGet()) {
            $categories = $filtresContainer->offsetExists('categories') ? $filtresContainer->categories : array();
            $prixmin = $filtresContainer->offsetExists('prixmin') ? $filtresContainer->prixmin : null;
            $prixmax = $filtresContainer->offsetExists('prixmax') ? $filtresContainer->prixmax : null;
            $etats = $filtresContainer->offsetExists('etats') ? $filtresContainer->etats : array();

            // Si des filtres sont en session, les vérifier avant de les utiliser.
            if (!empty($categories) || $prixmin !== null || $prixmax !== null || !empty($etats)) {
                $success = checkData($categoriesEnBase, $categories, $prixmin, $prixmax, $etatsEnBase, $etats);
            } else {
                $success = true;
                
                // Récupérer les prix min et max en base de donnée
                $qb = $em->createQueryBuilder();
                $qb->select('min(p.prix) as prixmin, max(p.prix) as prixmax')
                    ->from('Application\Model\Entity\Produit', 'p');
                $query = $qb->getQuery();
                $result = $query->getResult();
                $prixmin = $result[0]['prixmin'];
                $prixmax = $result[0]['prixmax'];
                
                // Cocher toutes les catégories et tous les états
                foreach ($categoriesEnBase as $c)   $categories[] = $c->getId();
                foreach ($etatsEnBase as $e)   $etats[] = $e->getId();
            }

            if ($success) {
                $produitsEnBase = getProductsWithFilters($em, $categories, $prixmin, $prixmax, $etats);
            }
        } else {
            $categories = $request->getPost('categories');
            $prixmin = $request->getPost('prixmin');
            $prixmax = $request->getPost('prixmax');
            $etats = $request->getPost('etats');
            
            $success = checkData($categoriesEnBase, $categories, $prixmin, $prixmax, $etatsEnBase, $etats);
            if ($success) {
                $produitsEnBase = getProductsWithFilters($em, $categories, $prixmin, $prixmax, $etats);
                
                // sauvegarde des filtres en sessions
                $filtresContainer->categories = $categories;
                $filtresContainer->prixmin = $prixmin;
                $filtresContainer->prixmax = $prixmax;
                $filtresContainer->etats = $etats;
            }
        }
        
        $moduleConfig = $this->getServiceLocator()->get('config');
        $file_path = $moduleConfig['application']['file_path'];
        $full_file_path = $moduleConfig['application']['full_file_path'];
        
        return new ViewModel(array(
            'categoriesEnBase' => $categoriesEnBase,
            'categories' => $categories,
            'prixmin' => $prixmin,
            'prixmax' => $prixmax,
            'etats' => $etats,
            'etatsEnBase' => $etatsEnBase,
            'produitsEnBase' => $produitsEnBase,
            'file_path' => $file_path,
            'full_file_path' => $full_file_path,
        ));
    }
    
    public function addAction()
    {
        $form = new \Application\Form\ProduitForm();
        $form->get('submit')->setValue('Add');

        $request = $this->getRequest();
        if ($request->isPost()) {
            //var_dump($this->getRequest());exit;
            $produit = new \Application\Model\Entity\Produit();
            $form->setInputFilter($produit->getInputFilter());
            $form->setData($request->getPost());

            if ($form->isValid()) {
                $produit->populate($form->getData());
                $this->getEntityManager()->persist($produit);
                $this->getEntityManager()->flush();

                // Redirect to list of albums
                return $this->redirect()->toRoute('produit');
            }
        }
        return array('form' => $form);
    }

    public function editAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('page', array(
                'action' => 'add'
            ));
        }
        $page = $this->getEntityManager()->find('Backoffice\Model\Entity\Page', $id);

        $form  = new \Backoffice\Form\PageForm();
        $form->bind($page);
        $form->get('submit')->setAttribute('value', 'Edit');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setInputFilter($page->getInputFilter());
            $form->setData($request->getPost());

            if ($form->isValid()) {
                $form->bindValues();
                $this->getEntityManager()->flush();

                // Redirect to list of albums
                return $this->redirect()->toRoute('page');
            }
        }

        return array(
            'id' => $id,
            'form' => $form,
        );
    }

    public function deleteAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('page');
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $del = $request->getPost('del', 'No');

            if ($del == 'Yes') {
                $id = (int) $request->getPost('id');
                $page = $this->getEntityManager()->find('Backoffice\Model\Entity\Page', $id);
                if ($page) {
                    $this->getEntityManager()->remove($page);
                    $this->getEntityManager()->flush();
                }
            }

            // Redirect to list of albums
            return $this->redirect()->toRoute('page');
        }

        return array(
            'id'    => $id,
            'page' => $this->getEntityManager()->find('Backoffice\Model\Entity\Page', $id)
        );
    }

}

